<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="政策名称" prop="policyName">
        <el-input
          v-model="queryParams.policyName"
          placeholder="请输入政策名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label="json格式的上下班时间段,但是存的是字符串, 应该手动解析数据" prop="workTimeJson">-->
      <!--  <el-input-->
      <!--    v-model="queryParams.workTimeJson"-->
      <!--    placeholder="请输入json格式的上下班时间段,但是存的是字符串, 应该手动解析数据"-->
      <!--    clearable-->
      <!--    @keyup.enter="handleQuery"-->
      <!--  />-->
      <!--</el-form-item>-->
      <!--<el-form-item label="打卡成功的容忍时间范围, 即在规定上班时间后N分钟内可以成功打卡,  在下班时间的前N分钟内不会被认为早退" prop="tolerateTimes">-->
      <!--  <el-input-->
      <!--    v-model="queryParams.tolerateTimes"-->
      <!--    placeholder="请输入打卡成功的容忍时间范围, 即在规定上班时间后N分钟内可以成功打卡,  在下班时间的前N分钟内不会被认为早退"-->
      <!--    clearable-->
      <!--    @keyup.enter="handleQuery"-->
      <!--  />-->
      <!--</el-form-item>-->
      <!--<el-form-item label="加班起始时间" prop="overtimeStart">-->
      <!--  <el-input-->
      <!--    v-model="queryParams.overtimeStart"-->
      <!--    placeholder="请输入加班起始时间"-->
      <!--    clearable-->
      <!--    @keyup.enter="handleQuery"-->
      <!--  />-->
      <!--</el-form-item>-->
      <!--<el-form-item label="每日标准工作时长" prop="workHoursPerDay">-->
      <!--  <el-input-->
      <!--    v-model="queryParams.workHoursPerDay"-->
      <!--    placeholder="请输入每日标准工作时长"-->
      <!--    clearable-->
      <!--    @keyup.enter="handleQuery"-->
      <!--  />-->
      <!--</el-form-item>-->
      <el-form-item label="政策描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入政策描述"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label="创建时间" prop="createdAt">-->
      <!--  <el-date-picker clearable-->
      <!--    v-model="queryParams.createdAt"-->
      <!--    type="date"-->
      <!--    value-format="YYYY-MM-DD"-->
      <!--    placeholder="请选择创建时间">-->
      <!--  </el-date-picker>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="更新时间" prop="updatedAt">-->
      <!--  <el-date-picker clearable-->
      <!--    v-model="queryParams.updatedAt"-->
      <!--    type="date"-->
      <!--    value-format="YYYY-MM-DD"-->
      <!--    placeholder="请选择更新时间">-->
      <!--  </el-date-picker>-->
      <!--</el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['attendance:policies:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['attendance:policies:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['attendance:policies:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['attendance:policies:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--展示表单-->
    <el-table v-loading="loading" :data="policiesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="考勤政策ID，主键" align="center" prop="id" />-->
      <el-table-column label="政策名称" align="center" prop="policyName" />
      <!--<el-table-column label="json格式的上下班时间段,但是存的是字符串, 应该手动解析数据" align="center" prop="workTimeJson" />-->
      <el-table-column label="上下班时间段" width="200">
        <template #default="{ row }">
          <WorkTimeDisplay
              :jsonStr="row.workTimeJson"
              :showTotal="true"
              :showJsonBtn="true"
          />
        </template>
      </el-table-column>
      <el-table-column label="打卡容忍时间(分钟)" align="center" prop="tolerateTimes" />
      <el-table-column label="加班起始时间(分钟)" align="center" prop="overtimeStart" />
      <el-table-column label="每日标准工作时长(小时)" align="center" prop="workHoursPerDay" />
      <el-table-column label="政策描述" align="center" prop="description" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['attendance:policies:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['attendance:policies:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考勤政策/排班详情对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="policiesRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="政策名称" prop="policyName">
          <el-input v-model="form.policyName" placeholder="请输入政策名称" />
        </el-form-item>

        <el-form-item label="上下班时间段" prop="workTimeJson">
          <!--<el-input v-model="form.workTimeJson" placeholder="请输入json格式的上下班时间段" />-->

          <WorkTimeEditor v-model="form.workTimeJson" />
        </el-form-item>

        <el-form-item label="打卡容忍时间(分钟)" prop="tolerateTimes">
          <el-input v-model="form.tolerateTimes" placeholder="请输入打卡成功的容忍时间范围, 即在规定上班时间后N分钟内可以成功打卡,  在下班时间的前N分钟内不会被认为早退" />
        </el-form-item>
        <el-form-item label="加班起始时间(分钟)" prop="overtimeStart">
          <el-input v-model="form.overtimeStart" placeholder="请输入加班起始时间" />
        </el-form-item>
        <!--<el-form-item label="每日标准工作时长" prop="workHoursPerDay">-->
        <!--  <el-input v-model="form.workHoursPerDay" placeholder="请输入每日标准工作时长" />-->
        <!--</el-form-item>-->
        <el-form-item label="政策描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入政策描述" />
        </el-form-item>
        <!--<el-form-item label="创建时间" prop="createdAt">-->
        <!--  <el-date-picker clearable-->
        <!--    v-model="form.createdAt"-->
        <!--    type="date"-->
        <!--    value-format="YYYY-MM-DD"-->
        <!--    placeholder="请选择创建时间">-->
        <!--  </el-date-picker>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="更新时间" prop="updatedAt">-->
        <!--  <el-date-picker clearable-->
        <!--    v-model="form.updatedAt"-->
        <!--    type="date"-->
        <!--    value-format="YYYY-MM-DD"-->
        <!--    placeholder="请选择更新时间">-->
        <!--  </el-date-picker>-->
        <!--</el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Policies">
import {addPolicies, delPolicies, getPolicies, listPolicies, updatePolicies} from "@/api/attendance/policies"
import WorkTimeDisplay from '@/views/attendance/components/WorkTimeDisplay.vue';
import WorkTimeEditor from "@/views/attendance/components/WorkTimeEditor.vue";
import {calculateTotalMinutes} from "@/views/attendance/utils/workTimeUtils.js";

const { proxy } = getCurrentInstance()

const policiesList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    policyName: null,
    workTimeJson: null,
    tolerateTimes: null,
    overtimeStart: null,
    workHoursPerDay: null,
    description: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    policyName: [
      { required: true, message: "政策名称不能为空", trigger: "blur" }
    ],
    workTimeJson: [
      { required: true, message: "上下班时间段不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询考勤政策/排班详情列表 */
function getList() {
  loading.value = true
  listPolicies(queryParams.value).then(response => {
    policiesList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    policyName: null,
    workTimeJson: null,
    tolerateTimes: null,
    overtimeStart: null,
    workHoursPerDay: null,
    description: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("policiesRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加考勤政策/排班详情"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPolicies(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改考勤政策/排班详情"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["policiesRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {

        console.log("原始表单:", JSON.parse(JSON.stringify(form.value)));
        console.log("workTimeJson:", form.value.workTimeJson);

        const totalMinutes = calculateTotalMinutes(form.value.workTimeJson);
        console.log("计算结果:", totalMinutes);

        // 转化结果为小时
        const hours = totalMinutes / 60;
        // 考虑到可能存在小数，保留二位小数
        const formattedHours = hours.toFixed(2);
        console.log("格式化结果:", formattedHours);
        // 检查是否为整数
        if (Number.isInteger(hours)) {
          form.value.workHoursPerDay = hours;
        } else {
          form.value.workHoursPerDay = formattedHours;
        }


        updatePolicies(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        console.log("原始表单:", JSON.parse(JSON.stringify(form.value)));
        console.log("workTimeJson:", form.value.workTimeJson);

        const totalMinutes = calculateTotalMinutes(form.value.workTimeJson);
        console.log("计算结果:", totalMinutes);

        // 转化结果为小时
        const hours = totalMinutes / 60;
        // 考虑到可能存在小数，保留二位小数
        const formattedHours = hours.toFixed(2);
        console.log("格式化结果:", formattedHours);
        // 检查是否为整数
        if (Number.isInteger(hours)) {
          form.value.workHoursPerDay = hours;
        } else {
          form.value.workHoursPerDay = formattedHours;
        }

// 显式转换类型
//         form.value.workHoursPerDay = String(totalMinutes);
        console.log("赋值后:", JSON.parse(JSON.stringify(form.value)));


        addPolicies(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除考勤政策/排班详情编号为"' + _ids + '"的数据项？').then(function() {
    return delPolicies(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('attendance/policies/export', {
    ...queryParams.value
  }, `policies_${new Date().getTime()}.xlsx`)
}

getList()
</script>
